package com.xzy.controller;

import com.xzy.pojo.Price;
import com.xzy.pojo.Product;
import com.xzy.pojo.ProductImage;
import com.xzy.service.InsertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by css on 2018/8/20.
 */
@Controller
public class InsertController {
    @Autowired
    private InsertService insertService;
    @RequestMapping("insert")
    @ResponseBody
    public Map insert(InsertBean insertBean, HttpServletRequest request){
        ServletContext servletContext = request.getServletContext();
        Integer productid = (Integer) servletContext.getAttribute("productid");
        Integer priceid = (Integer) servletContext.getAttribute("priceid");
        if(productid==null){
            productid=8;
            servletContext.setAttribute("productid",productid++);
        }
        if(priceid==null){
            priceid=20;
            servletContext.setAttribute("priceid",priceid++);
        }
        Product product=insertBean.getProduct();
        ProductImage productImage=insertBean.getProductImage();
        Price price=insertBean.getPrice();
        Map map=new HashMap();
        product.setId(productid);
        price.setId(priceid++);
        productImage.setId(UUID.randomUUID().toString().replaceAll("-",""));
        productImage.setProductId(productid);
        price.setProductId(productid);
        map.put("product",product);
        map.put("price",price);
        map.put("productImage",productImage);
        insertService.insert(product,productImage,price);
        servletContext.setAttribute("productid",++productid);
        servletContext.setAttribute("priceid",++priceid);
        return map;
    }
}
